import apiClient from './api'

// 文档接口定义
export interface Document {
  id: string
  name: string
  type: string
  size: number
  chunks: number
  uploadTime: string
  lastModified: string
  tags: string[]
  processed: boolean
  embeddingStatus: 'pending' | 'processing' | 'completed' | 'failed'
}

// 文档块接口定义
export interface DocumentChunk {
  id: string
  documentId: string
  content: string
  chunkIndex: number
  pageNumber?: number
  tokens: number
}

// 上传文档响应接口
export interface UploadDocumentResponse {
  documentId: string
  name: string
  uploadTime: string
  processingId: string
}

// 文档服务类
class DocumentService {
  // 上传文档
  async uploadDocument(file: File, tags: string[] = []): Promise<UploadDocumentResponse> {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('tags', JSON.stringify(tags))

    const response = await apiClient.post('/v1/documents/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response.data
  }

  // 获取文档列表
  async getDocuments(params?: {
    page?: number
    pageSize?: number
    search?: string
    type?: string
    tags?: string[]
    processed?: boolean
    sortBy?: string
    sortOrder?: 'asc' | 'desc'
  }) {
    const response = await apiClient.get('/v1/documents', { params })
    return response
  }

  // 获取文档详情
  async getDocumentDetail(documentId: string) {
    const response = await apiClient.get(`/v1/documents/${documentId}`)
    return response
  }

  // 获取文档块
  async getDocumentChunks(documentId: string, params?: {
    page?: number
    pageSize?: number
    search?: string
  }) {
    const response = await apiClient.get(`/v1/documents/${documentId}/chunks`, { params })
    return response
  }

  // 更新文档信息
  async updateDocument(documentId: string, data: {
    name?: string
    tags?: string[]
  }) {
    const response = await apiClient.put(`/v1/documents/${documentId}`, data)
    return response
  }

  // 删除文档
  async deleteDocument(documentId: string) {
    const response = await apiClient.delete(`/v1/documents/${documentId}`)
    return response
  }

  // 批量删除文档
  async batchDeleteDocuments(documentIds: string[]) {
    const response = await apiClient.delete('/v1/documents/batch', {
      data: { documentIds }
    })
    return response
  }

  // 下载文档
  async downloadDocument(documentId: string) {
    const response = await apiClient.get(`/v1/documents/${documentId}/download`, {
      responseType: 'blob'
    })
    return response
  }

  // 获取支持的文档类型
  async getSupportedDocumentTypes() {
    const response = await apiClient.get('/v1/documents/supported-types')
    return response
  }

  // 获取处理状态
  async getProcessingStatus(processingId: string) {
    const response = await apiClient.get(`/v1/documents/processing-status/${processingId}`)
    return response
  }
}

export default new DocumentService()